<template>
  <div>
    <h1>{{ websocketStatus }}</h1>
    <div class="student_box">
      <div class="student_item" v-for="(dl, indexD) in dataList" :key="indexD">
        <span
          class="student_name"
          style="margin-right: 10px; font-weight: 600; font-size: 20px"
          >{{ dl.name }}-</span
        >
        <span class="student_age">{{ dl.age }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue';
export default defineComponent({
  name: 'WebSocketC',
});
</script>
<script setup>
// import WebSocket from 'websocket';

const socket = new WebSocket('ws://localhost:8080/');

// status
const websocketStatus = ref('等待中...');

// data
const dataList = ref([]);

// onMounted
onMounted(() => {
  websocketStatus.value = '连接中....';

  // 建立连接
  socket.onopen = () => {
    console.log('WebSocket 已建立连接!');
    websocketStatus.value = '已连接!';
  };

  // 接收消息
  socket.onmessage = (event) => {
    console.log('收到消息:', event.data);
    dataList.value = JSON.parse(event.data);
  };

  // 关闭连接
  socket.onclose = () => {
    console.log('WebSocket 已断开连接!');
    websocketStatus.value = '已断开!';
  };
  console.log(WebSocket);
});

// onBeforeUnmount
onBeforeUnmount(() => {
  // 在组建销毁前关闭 WebSocket 连接
  if (socket) {
    socket.close();
  }
});
</script>

<style lang="scss" scoped></style>
